package cn.fl.project.service.impl;

import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.project.constant.PrjCstAccInfoConstant;

import com.alibaba.fastjson.JSON;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.fl.project.dto.PrjCstAccInfoDTO;
import cn.fl.project.condition.PrjBscInfoQueryCondition;
import cn.fl.project.condition.PrjCstAccInfoQueryCondition;
import cn.fl.project.api.IPrjCstAccInfoApiService;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjCstAccInfoService;
import cn.fl.project.transform.PrjCstAccInfoVOTransform;
import cn.fl.project.vo.PrjBscInfoVO;
import cn.fl.project.vo.PrjCstAccInfoVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import fl.inf.facade.api.ITransLogApi;
import fl.inf.facade.condition.InfTransLogQueryCondition;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 项目客户账户信息表 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class PrjCstAccInfoServiceImpl implements IPrjCstAccInfoService {

	/**
     * 日志
     */
    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(PrjCstAccInfoServiceImpl.class);
	
	/**
	 * 项目客户账户信息表 暴露服务
	 */
	@Autowired
	private IPrjCstAccInfoApiService prjCstAccInfoApiService;
	/**
     * 数据字典服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    @Autowired
    private IPrjBscInfoService  prjBscInfoService;
	@Autowired
	private ITransLogApi transLogApi;//日志表

	@Override
	public PrjCstAccInfoVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)) return null;
		PrjCstAccInfoDTO dto = this.prjCstAccInfoApiService.selectPrjCstAccInfoById(id);
		PrjCstAccInfoVO vo = PrjCstAccInfoVOTransform.toVO(dto);
		this.setDictData(vo);
		return vo;
	}

	@Override
	public Long add(PrjCstAccInfoVO entity) throws BaseException{
		if(null == entity) return null;
		return this.prjCstAccInfoApiService.addPrjCstAccInfo(PrjCstAccInfoVOTransform.toDTO(entity));
	}

	@Override
	public boolean removeByIds(List<Long> ids) throws BaseException{
		if(CollectionUtils.isEmpty(ids)) return false;
		return this.prjCstAccInfoApiService.removePrjCstAccInfoByIds(ids,CurrentThreadContext.getCurrentUserId());
	}

	@Override
	public boolean modify(PrjCstAccInfoVO entity) throws BaseException{
		if(null == entity) return false;
		return this.prjCstAccInfoApiService.modifyPrjCstAccInfo(PrjCstAccInfoVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
        PrjCstAccInfoQueryCondition condition=null;
        if(null == page) {
            page = new Pager();
            page.setCondition(new PrjCstAccInfoQueryCondition());
        }
		condition=(PrjCstAccInfoQueryCondition)page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		page=this.prjCstAccInfoApiService.searchPrjCstAccInfoListPage(page);
		if(CollectionUtils.isNotEmpty(page.getResultList())){
            List<PrjCstAccInfoVO> voList=PrjCstAccInfoVOTransform.toVOList((List<PrjCstAccInfoDTO>)page.getResultList());
            this.setDictData(voList);
            page.setResultList(voList);
        }
        return page;
	}
	
	@Override
	public List<PrjCstAccInfoVO> searchList(PrjCstAccInfoQueryCondition condition) throws BaseException{
		if(null == condition) condition=new PrjCstAccInfoQueryCondition();
		condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
		condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
		condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		List<PrjCstAccInfoVO> voList=PrjCstAccInfoVOTransform.toVOList(this.prjCstAccInfoApiService.searchPrjCstAccInfoList(condition));
		this.setDictData(voList);
		return voList;
	}
	
    /**
     * 添加数据字典名称
     * @param voList
     */
	public void setDictData(List<PrjCstAccInfoVO> voList){
		if(CollectionUtils.isEmpty(voList)) return;
		Map<String, String> chkRstCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), PrjCstAccInfoConstant.CODE_PRJ_CST_CHK_RST_CD);
		Map<String, String> certTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), PrjCstAccInfoConstant.CODE_PRJ_CST_CERT_TYP_CD);
		Map<String, String> accTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_GRP_CST_NP_ACC_TYP_CD);

		for(PrjCstAccInfoVO vo:voList){
			if (chkRstCdMap != null && chkRstCdMap.containsKey(vo.getChkRstCd())) {
				vo.setChkRstCdNm(chkRstCdMap.get(vo.getChkRstCd()));
			}

			if (certTypCdMap != null && certTypCdMap.containsKey(vo.getCertTypCd())) {
				vo.setCertTypCdNm(certTypCdMap.get(vo.getCertTypCd()));
			}

			if (accTypCdMap != null && accTypCdMap.containsKey(vo.getAccTypCd())) {
				vo.setAccTypCdNm(accTypCdMap.get(vo.getAccTypCd()));
			}
		}
	}

	/**
	 * 添加数据字典名称
	 * @param vo
	 */
	public void setDictData(PrjCstAccInfoVO vo){
		if(null == vo) return;
		Map<String, String> chkRstCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), PrjCstAccInfoConstant.CODE_PRJ_CST_CHK_RST_CD);
		Map<String, String> certTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), PrjCstAccInfoConstant.CODE_PRJ_CST_CERT_TYP_CD);

		if (chkRstCdMap != null && chkRstCdMap.containsKey(vo.getChkRstCd())) {
			vo.setChkRstCdNm(chkRstCdMap.get(vo.getChkRstCd()));
		}

		if (certTypCdMap != null && certTypCdMap.containsKey(vo.getCertTypCd())) {
			vo.setCertTypCdNm(certTypCdMap.get(vo.getCertTypCd()));
		}
	}
	
	/**
     * 查询数据字典
     * @param groupCd 组代码
     * @return List<KeyValueVO>
     */
    public List<KeyValueVO> searchCdList(String groupCd){
        return this.sysDictionaryApiService.getKvList(groupCd, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
    }

	/**
	 * 检验客户四要素
	 * @param condition
	 * @return
	 * @throws BaseException
	 */
	public DataResultVO validePrjCstAccInfo(PrjCstAccInfoQueryCondition condition) throws BaseException{
		try {
			DataResultDTO resultDTO = this.prjCstAccInfoApiService.validePrjCstAccInfo(condition);
			if (resultDTO != null) {
				BaseLogUtils.info(logger,"validePrjCstAccInfo","检验客户信息返回=="+ JSON.toJSONString(condition)+",结果="+resultDTO.getCode(),CurrentThreadContext.getCurrentUserName());
                return new DataResultVO(Integer.parseInt(resultDTO.getCode()), resultDTO.getInfo());
            } else {
				BaseLogUtils.info(logger,"validePrjCstAccInfo","检验客户信息失败=="+ JSON.toJSONString(condition),CurrentThreadContext.getCurrentUserName());
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "检验客户信息失败");
            }
		} catch (Exception e) {
			BaseLogUtils.info(logger,"validePrjCstAccInfo","检验客户信息异常=="+ JSON.toJSONString(condition),CurrentThreadContext.getCurrentUserName(),e);
			return new DataResultVO(BaseConstant.IS_YESNO_NO, "检验客户信息异常");
		}
	}

	@Override
    @Deprecated
	public PrjCstAccInfoVO selectByPrjId(Long id) throws BaseException {
		if(StringUtils.isEmpty(id)) return null;
		PrjCstAccInfoDTO dto = this.prjCstAccInfoApiService.selectPrjCstAccInfoByPrjId(id);
		PrjCstAccInfoVO vo = PrjCstAccInfoVOTransform.toVO(dto);
		this.setDictData(vo);
		return vo;
	}

	@Override
	public Pager searchPrjCstAccInfoPage(Pager page) throws BaseException {
		if (null == page) {
    		throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
    	}
		PrjBscInfoQueryCondition qc = new PrjBscInfoQueryCondition ();
		InfTransLogQueryCondition condition = new InfTransLogQueryCondition();
		 List<Long> PrjIds = new ArrayList<>();
		 List<Long> PrjIds1 = new ArrayList<>();
		Pager pager = this.prjCstAccInfoApiService.searchPrjCstAccInfoPage(page);
		List<PrjCstAccInfoDTO> list = (List<PrjCstAccInfoDTO>) pager.getResultList();
		if(CollectionUtils.isNotEmpty(list)){
			for (PrjCstAccInfoDTO prjCstAccInfoDTO : list) {
				PrjIds.add(prjCstAccInfoDTO.getPrjId());
				String insAccNo = prjCstAccInfoDTO.getInsAccNo();
				if(insAccNo != null){
					prjCstAccInfoDTO.setSignStatus("已签约");
					prjCstAccInfoDTO.setVerdictStatus("success");
				}else {
					prjCstAccInfoDTO.setSignStatus("未签约");
					prjCstAccInfoDTO.setVerdictStatus("error");
				}
			}
			/*condition.setPrjIdList(PrjIds);
		    condition.setAction("signAccount");//已签约的信息
			List<InfTransLogDTO> transLogs = this.transLogApi.findTransLogs(condition);
				   for (PrjCstAccInfoDTO prjCstAccInfoDTO : list){
						if(CollectionUtils.isNotEmpty(transLogs)){
							for (InfTransLogDTO infTransLogDTO : transLogs) {
								if(infTransLogDTO.getPrjId().equals(prjCstAccInfoDTO.getPrjId())){
									String action = infTransLogDTO.getAction();
									String status = infTransLogDTO.getStatus();
										if(action.equals("signAccount") &&status.equals("success")){
											prjCstAccInfoDTO.setSignStatus("已签约");
											prjCstAccInfoDTO.setVerdictStatus("success");
								        }
								}
						   }
						}
						if(StringUtils.isBlank(prjCstAccInfoDTO.getSignStatus())){
							prjCstAccInfoDTO.setSignStatus("未签约");
							prjCstAccInfoDTO.setVerdictStatus("error");
				        }
			}*/

			qc.setIdList(PrjIds);
			List<PrjBscInfoVO> bscInfoList = this.prjBscInfoService.searchPrjBscInfoList(qc);
			if(CollectionUtils.isNotEmpty(list)){
				for (PrjCstAccInfoDTO PrjCstAccInfoDTO : list){
					for (PrjBscInfoVO prjBscInfoVO : bscInfoList) {
						if(prjBscInfoVO.getId().equals(PrjCstAccInfoDTO.getPrjId())){
							PrjCstAccInfoDTO.setLsCntNo(prjBscInfoVO.getLsCntNo());
						}
					}
				}
			}
		}
    	return pager;
	}

    /**
     * 修改项目客户账户信息及校验
     *
     * @param condition
     * @return
     * @throws BaseException
     */
    @Override
    public DataResultVO modifyPrjAccInfo(PrjCstAccInfoQueryCondition condition) throws BaseException {
        DataResultDTO resultDTO = null;
        try {
            resultDTO = this.prjCstAccInfoApiService.modifyPrjAccInfo(condition);
        } catch (Exception e) {
            BaseLogUtils.info(logger, "modifyPrjAccInfo", "修改项目客户账户信息及校验Error:", CurrentThreadContext.getCurrentUserName(), e);
            resultDTO = new DataResultDTO(String.valueOf(BaseConstant.IS_YESNO_NO),"操作异常,"+e.getMessage());
        }
        BaseLogUtils.info(logger, "modifyPrjAccInfo", "狮桥助手，修改项目客户账户信息及校验:" + JSON.toJSONString(resultDTO), CurrentThreadContext.getCurrentUserName());
        return new DataResultVO(Integer.parseInt(resultDTO.getCode()), resultDTO.getInfo(), resultDTO.getData());
    }

	/**
	 * 校验四要素，不保存
	 *
	 * @param condition
	 * @return
	 * @throws BaseException
	 */
	@Override
	public DataResultVO snVerifyModifyPrjAccInfo(PrjCstAccInfoQueryCondition condition) throws BaseException {
		DataResultDTO resultDTO = null;
		try {
			resultDTO = this.prjCstAccInfoApiService.snVerifyModifyPrjAccInfo(condition);
		} catch (Exception e) {
			BaseLogUtils.info(logger, "modifyPrjAccInfo", "修改项目客户账户信息及校验Error:", CurrentThreadContext.getCurrentUserName(), e);
			resultDTO = new DataResultDTO(String.valueOf(BaseConstant.IS_YESNO_NO),"操作异常,"+e.getMessage());
		}
		BaseLogUtils.info(logger, "modifyPrjAccInfo", "狮桥助手，修改项目客户账户信息及校验:" + JSON.toJSONString(resultDTO), CurrentThreadContext.getCurrentUserName());
		return new DataResultVO(Integer.parseInt(resultDTO.getCode()), resultDTO.getInfo(), resultDTO.getData());
	}

	/**
	 * 获取资管机构换卡数据列表
	 * @param page
	 * @return
	 * @throws BaseException
	 */
	@Override
	public Pager searchAssetManagerChangeCard (Pager page) throws BaseException {
		if (null == page) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		Pager pager = this.prjCstAccInfoApiService.searchAssetManagerChangeCardPage(page);
		return pager;
	}

	/**
	 * 获取有换卡需求的资管机构列表
	 * @return
	 * @throws BaseException
	 */
	@Override
	public List<KeyValueVO> getInsIdListOfChangeCard () throws BaseException {
		return this.prjCstAccInfoApiService.getInsIdListOfChangeCard ();
	}

	@Override
	public List<SysDictionaryDTO> searchGroup (String sysCd, String orgCd, String codeGrpCd) throws BaseException {
		return this.sysDictionaryApiService.searchGroup(sysCd,orgCd,codeGrpCd);
	}
}
